package com.dqhl.smartstable.fragment;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dqhl.smartstable.R;
import com.dqhl.smartstable.activity.LoginActivity;
import com.dqhl.smartstable.base.BaseFragment;
import com.dqhl.smartstable.util.Config;
import com.dqhl.smartstable.util.Constant;
import com.dqhl.smartstable.util.Dlog;
import com.dqhl.smartstable.util.JPushUtil;
import com.dqhl.smartstable.util.JsonUtils;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;


/**
 * Created by mac on 16/10/13.
 * 首页
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {

    private TextView tv_top_center;
    private ImageView iv_msg;

    private TextView tv_protect; //设防
    private TextView tv_unprotect; //解防
    private TextView tv_cancel_alarm; //取消警报
    private ImageView iv_repair; //设备报修
    private ImageView iv_contact_service; //联系客服

    private String token; //用户token
    private String strSN; //箱子号SN
    private Vibrator vibrator;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        isLogin();

        registerBroadcastReceiver();
        initView(view);


        return view;
    }

    MessageReceiver messageReceiver;

    class MessageReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Constant.MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(Constant.KEY_MESSAGE);
                String extras = intent.getStringExtra(Constant.KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(Constant.KEY_MESSAGE + " : " + messge + "\n");
                if (!JPushUtil.isEmpty(extras)) {
                    showMsg.append(Constant.KEY_EXTRAS + " : " + extras + "\n");
                }
                // TODO 如果收到消息为某个值，就执行一个操作
                Dlog.e("收到推送msg为:" + messge);
                Dlog.e("收到推送extras为:" + extras);
                doRing();
            }
        }
    }

    ;

    private void registerBroadcastReceiver() {
        Dlog.e("-----------registerBroadcastReceiver--------------");
        messageReceiver = new MessageReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        intentFilter.addAction(Constant.MESSAGE_RECEIVED_ACTION);
        getActivity().registerReceiver(messageReceiver, intentFilter);
    }

    /**
     * 判断是否需要登录
     */
    private void isLogin() {
        token = sp.getString(Constant.TOKEN, "");
        Dlog.e("sp中token值为:" + token);
        if (TextUtils.isEmpty(token)) {
            forward(LoginActivity.class);
        }
    }

    private void initView(View view) {
        tv_top_center = (TextView) view.findViewById(R.id.tv_top_center);
        tv_top_center.setText("首 页");
        iv_msg = (ImageView) view.findViewById(R.id.iv_msg);

        tv_protect = (TextView) view.findViewById(R.id.tv_protect);
        tv_unprotect = (TextView) view.findViewById(R.id.tv_unprotect);
        tv_cancel_alarm = (TextView) view.findViewById(R.id.tv_cancel_alarm);
        iv_repair = (ImageView) view.findViewById(R.id.iv_repair);
        iv_contact_service = (ImageView) view.findViewById(R.id.iv_contact_service);

        iv_msg.setOnClickListener(this);
        tv_protect.setOnClickListener(this);
        tv_unprotect.setOnClickListener(this);
        tv_cancel_alarm.setOnClickListener(this);
        iv_repair.setOnClickListener(this);
        iv_contact_service.setOnClickListener(this);

        strSN = sp.getString(Constant.SN, "");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_msg:
//                overlay(ShowJPushMsgActivity.class);
                toast("暂无消息");
//                doRing();
                break;
            case R.id.tv_protect: //设防
                doProtect();
                break;
            case R.id.tv_unprotect: //解防
                doUnproject();
                break;
            case R.id.tv_cancel_alarm: //取消警报
                doCancelAlarm();
//                if (player != null) {
//                    player.stop();
//                }
//                vibrator.cancel();
                break;
            case R.id.iv_repair: //设备报修
                doRepair();
                break;
            case R.id.iv_contact_service: //联系客服
                doContactService();
                break;
        }
    }

    /**
     * 设备报修
     */
    private void doRepair() {
        // TODO: 16/10/17
        toast("设备报修");
    }

    /**
     * 联系客服
     */
    private void doContactService() {
        // TODO: 16/10/17
        toast("联系客服");
    }

    /**
     * 设防
     */
    private void doProtect() {
        showCustomLoadBar("加载中");
        Dlog.e("token:" + token + ";case_sign:" + strSN);
        RequestParams params = new RequestParams(Config.Api.protect);
        params.addBodyParameter("case_sign", strSN);
        params.addBodyParameter("token", token);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                String msg = JsonUtils.getMsg(result);
                String code = JsonUtils.getCode(result);
                toast(code);
                Dlog.e(msg);
                if ("2000".equals(msg)) {
                    tv_protect.setText("已设防");
                    tv_unprotect.setText("解防");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    /**
     * 解防
     */
    private void doUnproject() {
        showCustomLoadBar("加载中");
        Dlog.e("token:" + token + ";case_sign:" + strSN);
        RequestParams params = new RequestParams(Config.Api.unprotect);
        params.addBodyParameter("case_sign", strSN);
        params.addBodyParameter("token", token);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                String msg = JsonUtils.getMsg(result);
                String code = JsonUtils.getCode(result);
                toast(code);
                Dlog.e(msg);
                if ("2000".equals(msg)) {
                    tv_protect.setText("设防");
                    tv_unprotect.setText("已解防");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    /**
     * 取消警报
     */
    private void doCancelAlarm() {
        showCustomLoadBar("加载中");
        Dlog.e("token:" + token + ";case_sign:" + strSN);
        RequestParams params = new RequestParams(Config.Api.cancel_alarm);
        params.addBodyParameter("case_sign", strSN);
        params.addBodyParameter("token", token);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Dlog.e(result);
                String msg = JsonUtils.getMsg(result);
                String code = JsonUtils.getCode(result);
                toast(code);
                Dlog.e(msg);
                if (player != null) {
                    player.stop();
                }
                vibrator.cancel();
//                if ("2000".equals(msg)) {
//                    if (player != null) {
//                        player.stop();
//                    }
//                    vibrator.cancel();
//                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                hideCustomLoadBar();
            }
        });
    }

    public MediaPlayer player;

    private void doRing() {
        vibrator = (Vibrator) app.getSystemService(Service.VIBRATOR_SERVICE);
        long [] pattern = {100,400,100,400,100,400,100,400,100,400,100,400,100,400,100,400,100,400,100,400,100,400,100,400,100,400,100,400};   // 停止 开启 停止 开启
        vibrator.vibrate(pattern, 2);
        Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        player = new MediaPlayer();
        try {
            player.setDataSource(app, alert);
            final AudioManager audioManager = (AudioManager) app.getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
                player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
                player.setLooping(true);
                player.prepare();
                player.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (messageReceiver != null){
            getActivity().unregisterReceiver(messageReceiver);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (messageReceiver != null){
            getActivity().unregisterReceiver(messageReceiver);
        }
    }
}
